package com.hzpd.hainan.module.usercenter.fragment;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hzpd.hainan.R;
import com.hzpd.hainan.app.BaseFragment;
import com.hzpd.hainan.config.CODE;
import com.hzpd.hainan.custorm.CustomProgressDialog;
import com.hzpd.hainan.model.SuperEntity;
import com.hzpd.hainan.model.usercenter.EmptyEntity;
import com.hzpd.hainan.module.usercenter.acticity.LoginActivity;
import com.hzpd.hainan.net.Factory;
import com.hzpd.hainan.utils.LogUtils;
import com.hzpd.hainan.utils.ParamUtils;
import com.hzpd.hainan.utils.TUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/7/5.
 */

public class FindbackpwFragment extends BaseFragment {
    private static final String TAG = "FindbackpwFragment";
    @BindView(R.id.title_stilte_layout)
    TextView title_stilte_layout;
    @BindView(R.id.phone_et_findpw_fragment)
    EditText phone_et_findpw_fragment;
    @BindView(R.id.code_et_findpw_fragment)
    EditText code_et_findpw_fragment;
    private String phoneNumber;
    private String code;
    @BindView(R.id.tv_findpw_fragment)
    volatile TextView tv_findpw_fragment;
    @BindView(R.id.fpb_ll_veify)
    LinearLayout fpb_ll_veify;//验证码
    @BindView(R.id.reset_ll_findpw)
    LinearLayout reset_ll_findpw;//找回密码
    @BindView(R.id.btn_findpw_fragment)
    Button btn_findpw_fragment;

    @BindView(R.id.pw_1_findpw)
    EditText pw_1_findpw;
    @BindView(R.id.pw_2_findpw)
    EditText pw_2_findpw;
    @BindView(R.id.pw_3_findpw)
    EditText pw_3_findpw;
    @BindView(R.id.submit_findpw)
    Button submit_findpw;
    int type;
    private Timer timer;
    private int t = 120;
    private CustomProgressDialog dialog; // 载入中对话框
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 333: {
                    try {
                        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
                            tv_findpw_fragment.setText(t + "秒");
                        }else{
                            tv_findpw_fragment.setText(t + "སྐར་ཆ།");
                        }
                        t--;
                        if (t < 0) {
                            resetTimer();
                        }
                        disMissDialog();
                    }catch (Exception e){
                        e.printStackTrace();
                    }


                }
                break;
                case 444: {

                    verifyCorrect();
                    TUtils.toast("验证成功");
                }
                break;
                case 555: {
                    TUtils.toast("验证码错误");
                    code_et_findpw_fragment.setText("");

                    resetTimer();
                }
                break;
                case 445: {
                    TUtils.toast("验证码获取成功");

                    startTime();// 开启定时器
                }
                break;
                case 446: {
                    TUtils.toast("验证码获取失败");

                    resetTimer();
                }
                break;
            }
        }
    };

    @Override
    public int setMyContentView() {
        return R.layout.fragment_findpw;
    }

    @Override
    public void initView() {
        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            title_stilte_layout.setText("找回密码");
            phone_et_findpw_fragment.setHint("请输入手机号");
            code_et_findpw_fragment.setHint("请输入手机验证码");
            tv_findpw_fragment.setText("发送短信");
            btn_findpw_fragment.setText("下一步");

            pw_1_findpw.setHint("新密码");
            pw_2_findpw.setHint("确认新密码");
            submit_findpw.setText("确认");
        }else{
            title_stilte_layout.setText("གསང་གྲངས་འཚོལ་བ།");
            phone_et_findpw_fragment.setHint("ཁ་པར་ཨང་གྲངས།");
            code_et_findpw_fragment.setHint("ཁ་པར་གྱི་ར་སྤྲོད་ཨང་གྲངས།");
            tv_findpw_fragment.setText("ར་སྤྲོད་ཨང་གྲངས་ལེན་པ།");
            btn_findpw_fragment.setText("པར་ངོས་རྗེས་མ།");

            pw_1_findpw.setHint("གསང་གྲངས་གསར་བ།");
            pw_2_findpw.setHint("གསང་གྲངས་གཏན་འཁེལ།");
            submit_findpw.setText("གཏན་འཁེལ།");
        }
    }

    @Override
    public void initData() {

    }
    @OnClick(R.id.back_stitle_layout)
    public void goBack(View view){
        activity.onBackPressed();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Bundle bundle = getArguments();

        if (type == 2) {

//                fpb_et_pwd_id3.setVisibility(View.VISIBLE);
//                fpb_et_pwd_id3.setHint("再次输入新密码");
//                fpb_et_pwd_id.setHint("旧密码");
//                fpb_et_pwd_id2.setHint("新密码");
//                stitle_tv_content.setText("修改密码");
//                LogUtils.e("mobile-->"+spu.getUser().getMobile());
//                findback_phone.setText(spu.getUser().getMobile());
        }

        SMSSDK.registerEventHandler(new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {
                if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        //验证码获取成功
                        handler.sendEmptyMessage(445);
                    } else if (result == SMSSDK.RESULT_ERROR) {
                        handler.sendEmptyMessage(446);
                    }
                } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    if (result == SMSSDK.RESULT_COMPLETE) {
                        handler.sendEmptyMessage(444);
                    } else if (result == SMSSDK.RESULT_ERROR) {
                        handler.sendEmptyMessage(555);
                    }
                }
            }
        });

    }

    private void verifyCorrect() {
        fpb_ll_veify.setVisibility(View.GONE);
        reset_ll_findpw.setVisibility(View.VISIBLE);

    }
    private void showDialog() {
        if (dialog == null){
            dialog = CustomProgressDialog.createDialog(activity, false);
        }
        dialog.show();
    }
    private void disMissDialog(){
        if (dialog != null){
            dialog.dismiss();
        }
    }
    private void startTime() {
        tv_findpw_fragment.setBackgroundResource(R.drawable.register_getsms_shape);
        phone_et_findpw_fragment.setEnabled(false);
        tv_findpw_fragment.setClickable(false);
        if (timer != null) {
            timer.cancel();
        }

        timer = new Timer();
        TimerTask tt = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(333);
            }
        };
        timer.schedule(tt, 0, 1000);

    }
    private void resetTimer() {
        disMissDialog();
        if (null != timer) {
            timer.cancel();
        }
        if (spu.getLanguage().equals(CODE.ZHONGWEN)) {
            tv_findpw_fragment.setText("重新获取");
        }else{
            tv_findpw_fragment.setText("ཡང་བསྐྱར་ལེན་པ།");
        }
        tv_findpw_fragment.setBackgroundResource(R.drawable.btn_login);
        tv_findpw_fragment.setClickable(true);
        phone_et_findpw_fragment.setEnabled(true);
        t = 120;
    }

    @OnClick(R.id.tv_findpw_fragment)
    public void getCode(View view) {
        phoneNumber = phone_et_findpw_fragment.getText().toString().trim();
        if (phoneNumber == null || "".equals(phoneNumber)) {
            TUtils.toast("请输入手机号！");
            return;
        }
        if (phoneNumber.length() != 11) {
            TUtils.toast("手机号位数不对!");
            return;
        }
        tv_findpw_fragment.setClickable(false);

        SMSSDK.getVerificationCode("86", phoneNumber);
    }

    @OnClick(R.id.btn_findpw_fragment)
    public void Verify(View v) {
        String s = code_et_findpw_fragment.getText().toString().trim();

        if (s == null || "".equals(s)) {
            TUtils.toast("请输入验证码！");
            return;
        }

        SMSSDK.submitVerificationCode("86", phoneNumber, s);
        showDialog();
    }

    @OnClick(R.id.submit_findpw)
    public void changePassword(View v) {
        phoneNumber = phone_et_findpw_fragment.getText().toString().trim();

        String s = pw_1_findpw.getText().toString().trim();
        String s2 = pw_2_findpw.getText().toString().trim();
        String s3= pw_3_findpw.getText().toString().trim();

        if (type == 2){
            if (s == null || "".equals(s)) {
                TUtils.toast("请输入旧密码");
//				TUtils.toast(spu.getUser().getNickname());
                return;
            }
//			if (!s.equals(spu.getUser().getPassword())){
//				TUtils.toast("旧密码输入不正确");
//				return;
//			}
            if (s2 == null || "".equals(s2)) {
                TUtils.toast("请输入新密码");
                return;
            }
            if (s3 == null || "".equals(s3)) {
                TUtils.toast("请再次输入新密码");
                return;
            }
            if (!s2.equals(s3)){
                TUtils.toast("两次输入结果不一致");
                return;
            }

            if (s2.length() < 6) {
                TUtils.toast("密码不能太短");
                return;
            }
            if (s2.length() > 12) {
                TUtils.toast("密码不能太长");
                return;
            }
            showDialog();
            changePwd(s,s2);
        }else {
            if (s == null || "".equals(s)) {
                TUtils.toast("请输入密码");
                return;
            }
            if (s.length() < 6) {
                TUtils.toast("密码不能太短");
                return;
            }
            if (s.length() > 12) {
                TUtils.toast("密码不能太长");
                return;
            }
            if (s2 == null || "".equals(s2)) {
                TUtils.toast("请输入确认密码");
                return;
            }
            if (!s.equals(s2)) {
                TUtils.toast("俩次密码不一致！");
                pw_1_findpw.setText("");
                pw_2_findpw.setText("");
                return;
            }
            showDialog();
            findPwd(phoneNumber,s2);
        }
    }

    private void findPwd(String phone,String newPw) {
        Map<String,String> map=new HashMap<>();
        map.put("mobile",phone);

        map.put("password",newPw);
        Factory.provideHttpService().findPw(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity emptyEntity) {

                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity emptyEntity) {
                        disMissDialog();
                        TUtils.toast(emptyEntity.msg);
                        activity.finish();
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "throwable: "+throwable.getMessage());
                    }
                });
    }

    private void changePwd(String oldPw, String newPw) {
        Map<String,String> map=new HashMap<>();
        map.put("uid",spu.getUser().getUid());
        map.put("old_pwd", oldPw);
        map.put("new_pwd", newPw);
        Factory.provideHttpService().changePassWord(ParamUtils.getRequestParam(map))
                .onBackpressureBuffer()
                .subscribeOn(Schedulers.io())
                .filter(new Func1<EmptyEntity, Boolean>() {
                    @Override
                    public Boolean call(EmptyEntity emptyEntity) {
//                        if ("200".equals(emptyEntity.code)){
//                            return true;
//                        }
                        return true;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<EmptyEntity>() {
                    @Override
                    public void call(EmptyEntity emptyEntity) {
                        disMissDialog();
                        if ("200".equals(emptyEntity.code)){
                            TUtils.toast(emptyEntity.msg);
                        }else {
                            TUtils.toast(emptyEntity.msg);
                        }

                        activity.finish();
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });

    }
    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
        // 销毁回调监听接口
        SMSSDK.unregisterAllEventHandler();
        handler.removeCallbacks(null);
        super.onDestroy();
    }


}
